package com.zjw.zy.coreui.fragment.tips

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.zjw.zy.R
import com.zjw.zy.base.BaseFragment
import com.zjw.zy.coreui.fragment.adapter.TipSubViewAdapter
import com.zjw.zy.coreui.view.SearchView
import com.zjw.zy.ext.mainActivity
import com.zjw.zy.utils.ResourcesUtils
import com.zjw.zy.utils.WindowUtils
import com.zjw.zy.viewmodel.TipsViewModel

/**
 * @author     ：zhong.jw
 * @date       ：Created in 2022/11/2 9:10
 * @description： 所有tip类的父fragment
 */
class TipFragment : BaseFragment() {

    companion object {
        const val TIP_TOTAL_INDEX = 0
        const val TIP_LIST_INDEX = 1
    }

    private val mTipViewModel: TipsViewModel by viewModels({ this })

    private val mViewPager: ViewPager2 by lazy { findViewById(R.id.tip_fragment_sub_view) }
    private val mSearchView: SearchView by lazy { findViewById(R.id.fragment_tip_search) }
    private val mSubViewAdapter: TipSubViewAdapter by lazy { TipSubViewAdapter(this) }
    private var mCurrentItem = TIP_TOTAL_INDEX

    override fun onPageEnter() {
        WindowUtils.TopBar.showBack()
        WindowUtils.TopBar.hideAllRightButton()
        WindowUtils.TopBar.setTopBarLabelText(ResourcesUtils.getString(R.string.tips_nav_label))
        WindowUtils.FootBar.hide()

        mainActivity().setFullBackGround(R.color.fragment_tip_main_color)

        switchPage(mCurrentItem)
    }

    override fun onViewRestore(savedInstanceState: Bundle?) {

    }

    override fun onSubscribe() {

    }

    override fun onBindViewListener() {
        mSearchView.bindListener(object : SearchView.OnSearchListener {
            override fun onSearchTextChange(keyword: String) {
                if (keyword.isEmpty()) {
                    switchPage(TIP_TOTAL_INDEX)
                } else {
                    mTipViewModel.requireTipsByKeyword(keyword)
                    switchPage(TIP_LIST_INDEX)
                }
            }
        })
    }

    override fun onBindViewValue() {
        mViewPager.adapter = mSubViewAdapter
        mViewPager.isSaveEnabled = false
        mViewPager.isUserInputEnabled = false
    }

    override fun onFindView(rootView: View?) {

    }

    override fun onLayoutId(): Int {
        return R.layout.fragment_tips
    }

    override fun onPageExit() {
        //离开页面，保存一下
        mCurrentItem = mViewPager.currentItem
    }

    override fun onBackClick() {
        if (mViewPager.currentItem != TIP_TOTAL_INDEX) {
            switchPage(TIP_TOTAL_INDEX)
            return
        }
        super.onBackClick()
    }

    fun switchPage(position: Int) {
        if (position == mViewPager.currentItem || !isPageVisible) {
            return
        }
        mViewPager.setCurrentItem(position, true)
    }
}